<?php

/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.pescms.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */

namespace Core;

use Core\Abnormal\Abnormal as Abnormal;
use Core\Func\CoreFunc as CoreFunc;
use Core\Route\Route as Route;

/**
 * 初始化系统控制层
 * @author LazyPHP
 * @version 1.0
 */
class App {

    public function __construct() {

        spl_autoload_register(array($this, 'loader'));
        //实体化控制层
        $this->start();
    }

    /**
     * 加载必须的类名
     * @param type $className 加载类名
     */
    private function loader($className) {
        $unixPath = str_replace("\\", "/", $className);
        if (file_exists(PES_PATH . $unixPath . '.class.php')) {
            require PES_PATH . $unixPath . '.class.php';
        } else {
            exit(PES_PATH . $unixPath . '.class.php文件不存在!');
        }
    }

    /**
     * 执行指定模块
     * @todo 改进说明详细看line on 158 to 160注释
     */
    public function start() {
        $route = new Route();
        $route->index();

        try {
            $class = ITEM . "\\" . GROUP . "\\" . MODULE;
            $unixPath = str_replace("\\", "/", $class);
            if (!file_exists(PES_PATH . $unixPath . '.class.php')) {
                //此处为CMS扩展，分离为单独框架时必须去除
                $class = ITEM . "\\" . GROUP . "\\Content";
                $obj = new $class();
                throw new Abnormal(MODULE . "模型不存在");
            }
            $obj = new $class();

            if (!method_exists($obj, ACTION)) {
                throw new Abnormal(MODULE . "模型不存在" . ACTION . "方法");
            }
            $a = ACTION;
            $obj->$a();
            unset($a);
        } catch (Abnormal $e) {
            try {
                //让魔术方法可以调用
                if (!is_callable(array($obj, ACTION))) {
                    throw new Abnormal(MODULE . "模型不存在" . ACTION . "方法");
                }
                $a = ACTION;
                $obj->$a();
                unset($a);
            } catch (Abnormal $e) {
                try {
                    if (file_exists(THEME . '/' . GROUP . '/' . MODULE . '_' . ACTION . '.php')) {
                        include THEME . '/' . GROUP . '/' . MODULE . '_' . ACTION . '.php';
                    } else {
                        throw new Abnormal('无法加载文件');
                    }
                } catch (Abnormal $e) {
                    echo 'Message: ' . $e->getMessage();
                }
            }
        }
    }

}
